<?php
// +----------------------------------------------------------------------
// | RXThinkCMF框架 [ RXThinkCMF ]
// +----------------------------------------------------------------------
// | 版权所有 2017~2020 南京RXThinkCMF研发中心
// +----------------------------------------------------------------------
// | 官方网站: http://www.rxthink.cn
// +----------------------------------------------------------------------
// | Author: 牧羊人 <1175401194@qq.com>
// +----------------------------------------------------------------------

namespace app\admin\controller;

use app\admin\service\OfCompanyService;
use app\common\controller\Backend;
use think\Controller;
use think\facade\Db;
use think\facade\View;

/**
 * 客户管理-控制器
 * @author 牧羊人
 * @since: 2021/12/21
 * Class Ofcompany
 * @package app\admin\controller
 */
class Ofcompany extends Backend
{
    /**
     * 初始化方法
     * @author 牧羊人
     * @since: 2021/12/21
     */
    public function initialize()
    {
        parent::initialize(); // TODO: Change the autogenerated stub
        $this->model      = new \app\admin\model\OfCompany();
        $this->adminModel = new \app\admin\model\Admin();
        $this->service    = new OfcompanyService();
    }

    /**
     * 数据列表页
     * @return mixed
     * @since 2020/7/5
     * @author 牧羊人
     */
    public function index()
    {
        return parent::index(); // TODO: Change the autogenerated stub
    }

    /**
     * 数据列表页
     * @return mixed
     * @since 2020/7/5
     * @author 牧羊人
     */
    public function getList()
    {
        $name = input("name", '');
        $list = Db::name("of_company")->field("id,name as title")->where("name", "like", "%$name%")->where('mark',1)->select();
        return json_encode(['code' => 0, 'data' => $list]);
    }

    /**
     * 添加或编辑
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @author 牧羊人
     * @since 2020/7/3
     */
    public function edit()
    {
        if (IS_POST) {
            $id                       = input("id", '');
            $agent_id                 = input("agent_id", 0);
            $service_id               = input("service_id", 0);
            $peer_id                  = input("peer_id", 0);
            $data                     = [];
            $data['name']             = input("name");
            $data['peer_id']          = $peer_id;
            $data['agent_id']         = $agent_id;
            $data['service_id']       = $service_id;
            $data['contacts_name']    = input("contacts_name");
            $data['phone']            = input("phone");
            $data['address']          = input("address");
            $data['business_license'] = input("business_license");
            $data['corporate_idcard'] = input("corporate_idcard");
            $data['fee_reduction']    = input("fee_reduction", 0);
            $data['general_number']   = input("general_number");
            $data['acting_book']      = input("acting_book");
            $data['total_book']       = input("total_book");
            $data['fee_year']         = input("fee_year");
            $data['company_no']       = input('company_no');
            $data['remark']           = input('remark');
            //将图片文字 组成一个数组 又不能影响到原先的数组
            $data['ofcomany_other'] = input('ofcomany_other');
            $ofcomany_other_desc    = input('ofcomany_other_desc/a') ? input('ofcomany_other_desc/a') : [];
            $new_arr                = [];

            if (!empty($data['ofcomany_other'])) {
                $ofcomany_other_list = explode(',', $data['ofcomany_other']);
                foreach ($ofcomany_other_list as $key => $value) {
                    $new_arr[] = [
                        'img'  => $value,
                        'desc' => $ofcomany_other_desc[$key],
                    ];
                }
                $data['ofcomany_other'] = json_encode($new_arr);
            }

            // if (empty($agent_id)) {
            //     return message("需要选择代理人", false);
            // }

            //检测是否重名
            $check_name_map = [
                ['mark','=',1],
                ['name','=',$data['name']]
            ];
            if($id){
                $check_name_map[] = ['id','<>',$id];
            }
            $is_setname = $this->model->where($check_name_map)->value('id');
            if($is_setname){
                return message("名称已经存在", false);
            }

            if (!empty($id)) {
                $result = Db::name("of_company")->where("id", $id)->update($data);
            } else {
                $result = Db::name("of_company")->insert($data);
            }

            if ($result !== false) {
                return message("操作成功", true);
            } else {
                return message("操作失败", false);
            }
        }

        // 主公司列表
        $wh   = [];
        $wh[] = ['pid', '=', 0];
        $wh[] = ['mark', '=', 1];
        $list = $this->model->where($wh)->select()->toArray();
        View::assign("list", $list);
        $adminMod = new \app\admin\model\Admin();
        // 同行公司列表
        $wh       = [];
        $wh[]     = ['mark', '=', 1];
        $wh[]     = ['role_ids', '=', 5];
        $peerList = $adminMod->where($wh)->select()->toArray();
        View::assign("peerList", $peerList);

        // 代理人列表
        $wh        = [];
        $wh[]      = ['mark', '=', 1];
        $wh[]      = ['role_ids', 'like', "%4%"];
        $agentList = $adminMod->where($wh)->select()->toArray();
        View::assign("agentList", $agentList);

        // 业务人列表
        $wh          = [];
        $wh[]        = ['mark', '=', 1];
        $wh[]        = ['role_ids', '=', 3];
        $serviceList = $adminMod->where($wh)->select()->toArray();
        View::assign("serviceList", $serviceList);

        $info = [];
        $id   = input("get.id", 0);
        if ($id) {
            $info = $this->model->getInfo($id);
            if (!empty($info)) {
                $info['corporate_idcard'] = empty($info['corporate_idcard']) ? [] : explode(',', $info['corporate_idcard']);
                $info['acting_book']      = empty($info['acting_book']) ? [] : explode(',', $info['acting_book']);
                $info['ofcomany_other']   = empty($info['ofcomany_other']) ? [] : json_decode($info['ofcomany_other']);

                $info['business_license']   = empty($info['business_license']) ? [] : explode(',', $info['business_license']);
                $info['total_book']   = empty($info['total_book']) ? [] : explode(',', $info['total_book']);

            }
        } else {
            $data = func_get_args();
            if (isset($data[0])) {
                foreach ($data[0] as $key => $val) {
                    $info[$key] = $val;
                }
            }
        }
        View::assign("info", $info);
        return $this->render();
    }

    /**
     * 删除单条记录
     * @return array
     * @author 牧羊人
     * @date 2019/2/25
     */
    public function drop()
    {
        if (IS_POST) {
            $id      = input('post.id');
            $cg_info = Db::name("of_copyright")->where("company_id", $id)->where('mark', 1)->find();
            if (!empty($cg_info)) {
                return message("还有关联著作权数据,无法删除", false);
            }
            $pa_info = Db::name("of_patent")->where("company_id", $id)->where('mark', 1)->find();
            if (!empty($pa_info)) {
                return message("还有关联专利数据,无法删除", false);
            }
            $pr_info = Db::name("of_project")->where("company_id", $id)->where('mark', 1)->find();
            if (!empty($pr_info)) {
                return message("还有关联项目数据,无法删除", false);
            }
            $trademark_info = Db::name("of_trademark")->where("company_id", $id)->where('mark', 1)->find();
            if (!empty($trademark_info)) {
                return message("还有关联商标数据,无法删除", false);
            }
            $contract_info = Db::name("of_contract")->where("company_id", $id)->where('mark', 1)->find();
            if (!empty($contract_info)) {
                return message("还有关联合同数据,无法删除", false);
            }

            $info = $this->model->getInfo($id);
            if ($info) {
                $result = $this->model->drop($id);
                if ($result !== false) {
                    return message();
                }
            }
            return message($this->model->getError(), false);
        }
    }

    /**
     * 批量删除记录
     * @return array
     * @author 牧羊人
     * @date 2019/2/25
     */
    public function batchDrop()
    {
        $msg = '';
        if (IS_POST) {
            $ids = explode(',', $_POST['id']);
            //批量删除
            $num = 0;
            foreach ($ids as $key => $val) {
                $cg_info = Db::name("of_copyright")->where("company_id", $val)->where('mark', 1)->find();
                if (!empty($cg_info)) {
                    $msg .= "\n ID:" . $val . " : 还有关联著作权无法删除";
                    continue;
                }
                $pa_info = Db::name("of_patent")->where("company_id", $val)->where('mark', 1)->find();
                if (!empty($pa_info)) {
                    $msg .= "\n ID:" . $val . " : 还有关联专利无法删除";
                    continue;
                }
                $pr_info = Db::name("of_project")->where("company_id", $val)->where('mark', 1)->find();
                if (!empty($pr_info)) {
                    $msg .= "\n ID:" . $val . " : 还有关联项目无法删除";
                    continue;
                }
                $trademark_info = Db::name("of_trademark")->where("company_id", $val)->where('mark', 1)->find();
                if (!empty($trademark_info)) {
                    $msg .= "\n ID:" . $val . " : 还有关联商标无法删除";
                    continue;
                }
                $contract_info = Db::name("of_contract")->where("company_id", $val)->where('mark', 1)->find();
                if (!empty($contract_info)) {
                    $msg .= "\n ID:" . $val . " : 还有关联合同无法删除";
                    continue;
                }

                $res = $this->model->drop($val);
                if ($res !== false) {
                    $num++;
                }
            }

            return message('本次共选择' . count($ids) . "个条数据,删除" . $num . "个" . $msg, );
        }
    }

    /**
     * 数据列表页
     * @return mixed
     * @since 2020/7/5
     * @author 牧羊人
     */
    public function tab()
    {
        $company_id = input("company_id", 0);
        View::assign("company_id", $company_id);
        return $this->render();
    }

    /**
     * 批量添加数据列表页
     * https://blog.csdn.net/lmy1998/article/details/118420437 参考此处 原先导入的模式 因为7.4的原因语法报错
     * @return mixed
     * @since 2020/7/5
     * @author 牧羊人
     */
    public function batch_import()
    {
        if (IS_POST) {
            $param = request()->param();
            $data  = $this->getUrl($param['url']);
            if (!$data) {
                return message();
            }
            return message($data, false);
        } else {
            return $this->render();
        }

    }

    /**
     * 根据之前人写的业务逻辑  - 他只强制要求代理人必选  那此处就代理人+公司名称必写
     * 查重
     * 不能为空
     * 如果错误则不让导入
     */
    public function getUrl($path)
    {
        ini_set('max_execution_time', '0');
        $msg = '';

        $file = 'uploads/' . $path;
        if (!is_file($file)) {
            return "\n 请选择文件";
        }
        $data = $this->service->readFile($file, 1);
        if (!$data) {
            $msg .= "\n 没有可导入的数据,请确认导入的文件正确";
            return $msg;
        }

        $save_data = [];
        foreach ($data as $k => $item) {
            //判断模板是否正确
            if ($k == 1) {
                if ($item[0] !== '公司名称' || $item[1] !== '同行公司' || $item[2] !== '业务员' || $item[3] !== '代理人' || $item[7] !== '总委编号') {
                    $msg .= "\n 模板错误请选择正确的模板进行导入";
                    return $msg;
                }
                continue;
            }
            //跳过空行
            $is_empty = '';
            foreach ($item as $key => $value) {
                $is_empty .= $value;
            }
            if (!$is_empty) {
                continue;
            }
            //对必填的列判断
            if (empty($item[0])) {
                $msg .= "\n" . $k . "行:公司名称不能为空";
                return $msg;
            }
            // if (empty($item[3])) {
            //     $msg .= "\n" . $k . "行:代理人不能为空";
            //     return $msg;
            // }
            //代理人必填 且需要查询出id
            $agent_id = 0;
            if ($item[3]) {
                $agent_id = $this->adminModel->where('realname', $item[3])->where('mark', 1)->value('id');
                if (!$agent_id) {
                    $msg .= "\n" . $k . "行:代理人未匹配";
                    return $msg;
                }
            }

            //存在同行公司才匹配
            if (!$item[1]) {
                $peer_id = 0;
            } else {
                $peer_id = $this->adminModel->where('realname', $item[1])->where('mark', 1)->value('id');
                if (!$peer_id) {
                    $msg .= "\n" . $k . "行:同行公司未匹配";
                    return $msg;
                }
            }
            //存在业务员才查是否匹配
            if (!$item[2]) {
                $service_id = 0;
            } else {
                $service_id = $this->adminModel->where('realname', $item[2])->where('mark', 1)->value('id');
                if (!$service_id) {
                    $msg .= "\n" . $k . "行:业务员未匹配";
                    return $msg;
                }
            }

            //优先查重表格
            $excel_map = [
                ['name' => $item[0]],
            ];
            $is_excel_set = $this->service->checkDuplicate($excel_map, $save_data);
            if ($is_excel_set) {
                $msg .= "\n" . $k . "行:重复(当前导入的表格中公司名称已存在)";
                return $msg;
            }

            //查重  总委编号不是一开始就有的 只能根据名字查重
            $map = [
                ['mark', '=', 1],
                ['name', '=', $item[0]],
            ];
            $is_id = $this->model->where($map)->value('id');
            // if ($is_set) {
            //     $msg .= "\n" . $k . "行:重复（数据库中公司名称已存在）";
            //     return $msg;
            // }

            //如果是重复的 则总委编号的查重需要排除自己

            //如果输入了总委编号则查重
            if ($item[7]) {
                //优先查重表格
                $excel_map = [
                    ['general_number' => $item[7]],
                ];
                $is_excel_set = $this->service->checkDuplicate($excel_map, $save_data);
                if ($is_excel_set) {
                    $msg .= "\n" . $k . "行:重复(当前导入的表格中总委编号已经存在)";
                    return $msg;
                }

                //查重  总委编号不是一开始就有的 只能根据名字查重
                $map = [
                    ['mark', '=', 1],
                    ['general_number', '=', $item[7]],
                ];
                if ($is_id) {
                    $map[] = ['id', '<>', $is_id];
                }
                $is_set = $this->model->where($map)->value('id');
                if ($is_set) {
                    $msg .= "\n" . $k . "行:重复(数据库中总委编号已经存在)";
                    return $msg;
                }

            }

            $data = [
                'name'             => $item[0],
                'peer_id'          => $peer_id,
                'service_id'       => $service_id,
                'agent_id'         => $agent_id,
                'contacts_name'    => $item[4],
                'phone'            => $item[5],
                'address'          => $item[6],
                'general_number'   => $item[7],
                'fee_year'         => $item[8],
                'remark'           => $item[9],
                'create_time'      => time(),
                'update_time'      => time(),
                //此处text类型的字段设置了not null 不给默认报错 不改库的时候此处加就可
                'corporate_idcard' => '',
            ];
            if ($is_id) {
                $data['id'] = $is_id;

                foreach ($data as $key => $value) {
                    if (!$value) {
                        unset($data[$key]);
                    }
                }
            }
            $save_data[] = $data;
        }

        if (!$save_data) {
            $msg .= "\n 没有可导入的数据,请确认导入的文件正确";
            return $msg;
        }
        //
        $res = $this->model->saveAll($save_data);
        if ($res) {
            $msg .= "";
        } else {
            $msg .= "\n 插入未知错误";
        }
        return $msg;
    }

    public function download()
    {
        ini_set('max_execution_time', '0');
        $param = request()->param();
        // 查询要导出的数据
        $map = [
            ['mark', '=', 1],
        ];
        if ($param['name']) {
            $map[] = ['name', 'like', '%' . $param['name'] . '%'];
        }

        $admin_id = session("adminId");
        $role_id  = Db::name("admin")->where('id', '=', $admin_id)->value("role_ids");
        $arr_role = explode(",", $role_id);
        if (count($arr_role) == 1) {
            if ($role_id == 3) {
                $map[] = ['service_id', 'like', "%$admin_id%"];
            } else if ($role_id == 4) {
                $map[] = ['agent_id', 'like', "%$admin_id%"];
            } else if ($role_id == 5) {
                $map[] = ['peer_id', '=', $admin_id];
            }
        } else {
            $map[] = ['service_id', 'like', "%$admin_id%"];
        }

        $head = [
            ['title' => '公司名称', 'width' => 50],
            ['title' => '同行公司', 'width' => 50],
            ['title' => '业务员', 'width' => 15],
            ['title' => '代理人', 'width' => 15],
            ['title' => '联系人', 'width' => 15],
            ['title' => '电话', 'width' => 20],
            ['title' => '地址', 'width' => 50],
            ['title' => '总委编号', 'width' => 15],
            ['title' => '费减备案年份', 'width' => 15],
            ['title' => '备注', 'width' => 50],
        ];

        $data = $this->model->where($map)->order('id desc')->select();

        $new_data = [];
        foreach ($data as $key => $v) {
            $tmp = [];
            //同行公司 名称获取
            $tong_name = Db::name("admin")->where("id", $v['peer_id'])->value('realname');
            //业务员
            $ye_name = Db::name("admin")->where("id", $v['service_id'])->value('realname');
            //代理
            $agent_name = Db::name("admin")->where("id", $v['agent_id'])->value('realname');

            $tmp[] = $v['name'];
            $tmp[] = $tong_name;
            $tmp[] = $ye_name;
            $tmp[] = $agent_name;
            $tmp[] = $v['contacts_name'];
            $tmp[] = $v['phone'];
            $tmp[] = $v['address'];
            $tmp[] = $v['general_number'];
            $tmp[] = $v['fee_year'];
            $tmp[] = $v['remark'];

            $new_data[] = $tmp;
        }
        $fileName = '客户(' . date("Y-m-d H:i:s") . ')';
        $this->service->exportExcel($head, $new_data, $fileName);
    }
}
